// pages/modievent/modievent.js
const util = require('../../utils/util.js')
let app=getApp();
const plugin = requirePlugin('WechatSI');
const manager = plugin.getRecordRecognitionManager();
Page({

    //页面的初始数据
    data: {
        eventid:null,
        openid:null,
        titleinfo:null,
        imgurl:[],
        articleinfo:"",
        files:[],
        eventtime:null,
        date:null,
        dialogShow: false,
        eventimp:0,
        teasize:{
            maxHeight: 200,
             minHeight: 100
        },
        recordState: false, //录音状态
        animationData1: "",
       animationData2: "",
      animationStatus: false
    },
    //获取标题资源
    gettitle(t)
    {
        console.log(t.detail);
        this.data.titleinfo=t.detail;
    },
    //获取事件详情资源
    getarticle(a)
    {
       this.data.articleinfo=a.detail;
    },
    //获取图片上传信息
    chooseImage: function (e) {
        var that = this;
        wx.chooseImage({
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                that.setData({
                    files: res.tempFilePaths
                });
            }
        })
    },
    previewImage: function(e){
        wx.previewImage({
            current: e.currentTarget.id, // 当前显示图片的http链接
            urls: this.data.files // 需要预览的图片http链接列表
        })
    },
    selectFile(files) {
       console.log('files', files)
        // 返回false可以阻止某次文件上传
    },
    uplaodFile(files) {
        var that = this
        var fileList = files.tempFilePaths
        // 文件上传的函数，返回一个promise
        return new Promise((resolve, reject) => {
            wx.uploadFile({
              url: app.globalData.url+"/upload",
              filePath: fileList[0],
              name: 'file',
              formData: 
              {
              },
              header: {  
                "Content-Type": "multipart/form-data"  
              },
              timeout: 30000,
              success: (res) => {
                const data = JSON.parse(res.data)
                that.data.imgurl.push(data);
                console.log( that.data.imgurl);
                  resolve({urls: [data.data]});
              },
              fail: () => {
                reject('失败....')
              },
            })
        })
       
    },
    uploadError(e) {
        console.log('upload error', e.detail);
        wx.showToast({
          title: '图片过大!',
          icon:"error"
        })
    },
    uploadSuccess(e) {
        console.log('upload success', e.detail)
    },
    // 生命周期函数--监听页面加载
    onLoad: function (options) {
       this.initRecord();
        this.setData({
            selectFile: this.selectFile.bind(this),
            uplaodFile: this.uplaodFile.bind(this)
        })
    },
    //语音识别
    initRecord: function () {
      const that = this;
      // 有新的识别内容返回，则会调用此事件
      manager.onRecognize = function (res) {
        console.log(res)
      },
      manager.onStart = function (res) {
        console.log("成功开始录音识别", res)
      },
      manager.onError = function (res) {
        console.error("error msg", res)
      } ,
      manager.onStop = function (res) {
        if (res.result == '') {
          wx.showModal({
            title: '提示',
            content: '听不清楚，请重新说一遍！',
            showCancel: false,
            success: function (res) {}
          })
          return;
        }
        var text = that.data.articleinfo + res.result;
        that.setData({
          articleinfo: text
        })
      }
    },
    touchStart: function (e) {
      this.setData({
        recordState: true  //录音状态
      })
      // 语音开始识别
      manager.start({
        lang: 'zh_CN',// 识别的语言，目前支持zh_CN en_US zh_HK sichuanhua
      })
    },
    touchEnd: function (e) {
      this.setData({
        recordState: false
      })
      // 语音结束识别
      manager.stop();
    },
  
    //获取事件id
    geteventid()
    {
        var result = "";
        var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        var charactersLength = characters.length;
        for (var i = 0; i < 4; i++) {
          result += characters.charAt(
            Math.floor(Math.random() * charactersLength)
          );
        }
        var dat = util.formatDate(new Date());
    // 再通过setData更改Page()里面的data，动态更新页面的数据
      this.data.date=dat.replace(/-/g, "");
      this.data.eventid=result+this.data.date
      this.data.date= util.formatTime(new Date());
    },
    //switch按钮获取重要性
    switchChange(e){
        console.log(e.detail);
        if(e.detail>3)
        {
            this.data.eventimp=1;
        }
    },
//添加事件
updateevent()
{
    console.log()
    let that=this;
    that.geteventid();
    that.data.openid=app.globalData.openid;
    console.log(that.data.date);
    that.data.openid=app.globalData.openid;
    wx.request({
     url:app.globalData.url+'/addevent', 
     header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
     data: {
         eventid:that.data.eventid,
         openid:that.data.openid,
         eventtitle:that.data.titleinfo,
         eventarticle:that.data.articleinfo,
         eventtime: that.data.date,
         eventimp:that.data.eventimp
      },
      method: 'post',
      success: function (res) {
           console.log("成功");
           console.log(res);
           wx.showToast({
             title: '添加成功！',
             icon:"success"
           })
      },
      fail:function(err){//请求失败之后要做什么
         console.log('请求失败')
         }
         
 })
 //添加图片
 for(var i = 0; i < that.data.imgurl.length; i++) {
 wx.request({
    url:app.globalData.url+'/addpic', 
    header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
    data: {
        eventid:that.data.eventid,
        openid:that.data.openid,
       eventpicture:that.data.imgurl[i].data,
       pictime:that.data.date,
       leixing:that.data.imgurl[i].imageClassification
     },
     method: 'post',
     success: function (res) {
          let shu=(i+1)/that.data.imgurl.length;
         wx.showToast({
           title: '正在记录中！'+shu+'%',
           icon:"loading",
           duration:1000
         })  
     },
     fail:function(err){//请求失败之后要做什么
        console.log('请求失败');
        }  
})
 }
 setTimeout(that.gopast,1000);
},
//跳转到过去页面
gopast()
{
  wx.switchTab({
    url: '/pages/current/current',
  })
},
//动画
animationFun:function(animationData){
  if(!this.data.animationStatus){
    return 
  }
  var animation = wx.createAnimation({
    duration: 1000
  })
  animation.opacity(0).scale(2, 2).step(); 
  this.setData({
    [`${animationData}`]: animation.export()
  })
},
animationEnd: function (animationData) {
  var animation = wx.createAnimation({
    duration: 0
  })
  animation.opacity(1).scale(1, 1).step(); 
  this.setData({
    [`${animationData}`]: animation.export()
  })
},
recodeEnd: function() {
  //动画1结束
  var animation1 = wx.createAnimation({
    duration: 0
  })
  animation1.opacity(1).scale(1, 1).step(); 
  //动画2结束
  var animation2 = wx.createAnimation({
    duration: 0
  })
  animation2.opacity(1).scale(1, 1).step(); 
  this.setData({
    animationData1: animation1.export(),
    animationData2: animation2.export(),
    animationStatus: false
  })
},
recodeClick: function() {
  this.setData({
    animationStatus: true
  })
  this.animationFun('animationData1')
  setTimeout(()=>{
    this.animationFun('animationData2')
  },500)
  setTimeout(() => {
    this.animationRest()
  }, 1000)
},
animationRest: function() {
  //动画重置
  this.animationEnd('animationData1')
  setTimeout(()=>{
    this.animationEnd('animationData2')
  },500)
  setTimeout(() => {
    if (this.data.animationStatus) {
      this.recodeClick()
    }
  }, 100)
}
})
// 模糊搜索：https://www.cnblogs.com/daipianpian/articles/9258834.html